package com.xhs.controller;

import com.xhs.dto.*;
import com.xhs.model.QrCodeResult;
import com.xhs.model.SearchTask;
import com.xhs.service.PlaywrightService;
import com.xhs.service.SearchNotesService;
import com.xhs.service.TaskService;
import com.xhs.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 登录控制器
 *
 * @author xhs
 */
@Slf4j
@RestController
@RequestMapping("/api/login")
@Validated
@Tag(name = "登录管理", description = "小红书登录相关接口")
public class LoginController {

    @Autowired
    private PlaywrightService playwrightService;

    @Autowired
    private SearchNotesService searchNotesService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;

    /**
     * 输入手机号接口
     */
    @Operation(summary = "输入手机号发送验证码", description = "打开浏览器窗口，导航到小红书官网并输入手机号")
    @PostMapping("/input-phone")
    public XhsResponse<Map<String, Object>> inputPhone(@Valid @RequestBody PhoneInputRequest request) {
        log.info("收到手机号输入请求: {}", request.getPhoneNumber());

        Map<String, Object> result = playwrightService.inputPhoneNumber(request.getPhoneNumber());

        return XhsResponse.success("手机号输入成功", result);
    }

    /**
     * 验证码登录接口
     */
    @Operation(summary = "验证码登录", description = "在已输入手机号的基础上，输入验证码完成登录")
    @PostMapping("/verify-login")
    public XhsResponse<LoginResponse> verifyLogin(@Valid @RequestBody VerifyLoginRequest request) {
        log.info("收到验证码登录请求: {}", request.getPhoneNumber());

        String responseContent = playwrightService.verifyLogin(request.getPhoneNumber(), request.getVerifyCode());

        // 查找对应的会话
        String sessionId = playwrightService.getSessionIdByPhoneNumber(request.getPhoneNumber());

        LoginResponse loginResponse = LoginResponse.success(sessionId, request.getPhoneNumber(), responseContent);

        return XhsResponse.success("登录成功", loginResponse);
    }

    /**
     * 直接登录接口
     */
    @Operation(summary = "直接登录", description = "通过手机号和密码直接登录，如果MySQL中有cookie则直接返回成功")
    @PostMapping("/direct-login")
    public XhsResponse<LoginResponse> directLogin(@Valid @RequestBody DirectLoginRequest request) {
        log.info("收到直接登录请求: {}", request.getPhoneNumber());

        // 检查MySQL中是否有该手机号的cookies
        if (userService.hasCookie(request.getPhoneNumber())) {
            log.info("MySQL中存在cookies，直接登录成功: {}", request.getPhoneNumber());
            
            LoginResponse loginResponse = LoginResponse.success(
                "direct-login-" + System.currentTimeMillis(),
                request.getPhoneNumber(),
                "直接登录成功，使用已存储的登录状态"
            );
            
            return XhsResponse.success("直接登录成功", loginResponse);
        } else {
            log.info("MySQL中不存在cookies，需要重新登录: {}", request.getPhoneNumber());
            return XhsResponse.error("登录状态已过期，请重新登录");
        }
    }

    /**
     * 创建搜索任务
     */
    @Operation(summary = "创建搜索任务", description = "创建一个后台搜索任务，支持多个关键词")
    @PostMapping("/create-task")
    public XhsResponse<Long> createTask(@Valid @RequestBody CreateTaskRequest request) {
        log.info("收到创建任务请求: {}", request);

        Long taskId = taskService.createTask(request.getPhoneNumber(), request.getTaskName(), request.getKeywords());

        return XhsResponse.success("任务创建成功", taskId);
    }

    /**
     * 获取用户任务列表
     */
    @Operation(summary = "获取任务列表", description = "获取用户的所有搜索任务")
    @PostMapping("/tasks")
    public XhsResponse<List<SearchTask>> getTasks(@Valid @RequestBody TasksRequest request) {
        log.info("收到获取任务列表请求: phoneNumber={}", request.getPhoneNumber());

        List<SearchTask> tasks = taskService.getUserTasks(request.getPhoneNumber());

        return XhsResponse.success("获取任务列表成功", tasks);
    }

    /**
     * 获取任务执行结果
     */
    @Operation(summary = "获取任务结果", description = "获取指定任务的二维码扫描结果")
    @PostMapping("/task-results")
    public XhsResponse<List<QrCodeResult>> getTaskResults(@Valid @RequestBody TaskResultsRequest request) {
        log.info("收到获取任务结果请求: phoneNumber={}, taskName={}", request.getPhoneNumber(), request.getTaskName());

        List<QrCodeResult> results = taskService.getTaskResultsByName(request.getPhoneNumber(), request.getTaskName());
        return XhsResponse.success("获取任务结果成功", results);
    }

    /**
     * 搜索笔记（保留原接口兼容性）
     */
    @Operation(summary = "搜索笔记", description = "根据关键词搜索小红书笔记，自动检测微信二维码并下载")
    @PostMapping("/search-notes")
    public XhsResponse<SearchNotesResponse> searchNotes(@Valid @RequestBody SearchNotesRequest request) {
        log.info("收到搜索笔记请求: {}", request);

        SearchNotesResponse result = searchNotesService.searchNotes(request.getPhoneNumber(), request.getKeyword(), request.getPage());

        return XhsResponse.success("搜索完成，找到" + result.getTotalCount() + "个微信二维码图片", result);
    }

} 